package snake;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;


class Controller implements KeyListener, Runnable{
    Grid grid;
    GameView gameView;
    private boolean running;

    Controller(Grid grid, GameView gameView){
        this.grid = grid;
        this.gameView = gameView;
        this.running = true;
    }
    @Override
    public void keyTyped(KeyEvent e) {

    }

    @Override
    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();
        if (keyCode == KeyEvent.VK_UP){
            grid.changeDirection(Direction.UP);
        }
        if (keyCode == KeyEvent.VK_RIGHT){
            grid.changeDirection(Direction.RIGHT);
        }
        if (keyCode == KeyEvent.VK_DOWN){
            grid.changeDirection(Direction.DOWN);
        }
        if (keyCode == KeyEvent.VK_LEFT){
            grid.changeDirection(Direction.LEFT);
        }
        //repaint the canvas
        gameView.draw();
    }

    @Override
    public void keyReleased(KeyEvent e) {

    }

    @Override
    public void run() {
        while (running) {
            try {
                Thread.sleep(Settings.DEFAULT_MOVE_INTERVAL);
            } catch (InterruptedException e) {
                break;
            }
            running = grid.nextRound();
            if (running) {
                gameView.draw();
            }
            else{
                if (grid.getScore() > grid.returnRecord()) {
                    try {
                        grid.changeRecord(grid.getScore());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                gameView.showGameOverMessage();
            }

        }

        running = false;
    }

}
